package com.football.net.widget;


import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.football.net.R;
import com.football.net.bean.SquarePicBean;
import com.football.net.common.constant.HttpUrlConstant;
import com.football.net.common.util.CommonUtils;
import com.football.net.common.util.LogUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.List;

/**
 * @author wsf
 * @ClassName MultiImageView.java
 * @Description: 显示1~N张图片的View
 */

public class MultiImageView extends LinearLayout {
    public static int MAX_WIDTH = 0;

    private Context mContext;

    // 照片的Url列表
    private List<SquarePicBean> imagesList;

    //1:图文2音频3视频4链接
    private int dynamicType;

    /**
     * 长度 单位为Pixel
     **/
    private int videoMaxWandH;//视频图片允许的最大宽度
    private int pxOneMaxWandH;  // 单张图最大允许宽高
    private int pxMoreWandH = 0;// 多张图的宽高
    private int pxImagePadding = DensityUtils.dip2px(getContext(), 5);// 图片间的间距

    private int MAX_PER_ROW_COUNT = 3;// 每行显示最大数

    private LayoutParams onePicPara, videoPicPara;
    private LayoutParams morePara, moreParaColumnFirst;
    private LayoutParams rowPara;
    private RelativeLayout.LayoutParams videoTypePara, videoTypeRela;

    private OnItemClickListener mOnItemClickListener;

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    public MultiImageView(Context context) {
        super(context);
        this.mContext = context;
    }

    public MultiImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
    }

    public void setList(List<SquarePicBean> lists, int dynamicType) throws IllegalArgumentException {
        if (lists == null) {
            throw new IllegalArgumentException("imageList is null...");
        }
        imagesList = lists;
        this.dynamicType = dynamicType;

        if (MAX_WIDTH > 0) {
            pxMoreWandH = (MAX_WIDTH - pxImagePadding * 2) / 3; //解决右侧图片和内容对不齐问题
            pxOneMaxWandH = MAX_WIDTH * 2 / 3;
            videoMaxWandH = MAX_WIDTH;
            initImageLayoutParams();
        }
        initView();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (MAX_WIDTH == 0) {
            int width = measureWidth(widthMeasureSpec);
            if (width > 0) {
                MAX_WIDTH = width;
                if (imagesList != null && imagesList.size() > 0) {
                    setList(imagesList, 1);
                }
            }
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    /**
     * Determines the width of this view
     *
     * @param measureSpec A measureSpec packed into an int
     * @return The width of the view, honoring constraints from measureSpec
     */
    private int measureWidth(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            // We were told how big to be
            result = specSize;
        } else {
            // Measure the text
            // result = (int) mTextPaint.measureText(mText) + getPaddingLeft()
            // + getPaddingRight();
            if (specMode == MeasureSpec.AT_MOST) {
                // Respect AT_MOST value if that was what is called for by
                // measureSpec
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

    private void initImageLayoutParams() {
//        int wrap = LayoutParams.WRAP_CONTENT;
        int wrap = DensityUtils.dip2px(getContext(), 150);
        int match = LayoutParams.MATCH_PARENT;

        onePicPara = new LayoutParams(pxOneMaxWandH, wrap);
        videoPicPara = new LayoutParams(videoMaxWandH, videoMaxWandH * 2 / 3);
        videoTypePara = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        videoTypeRela = new RelativeLayout.LayoutParams(videoMaxWandH, videoMaxWandH * 2 / 3);

        moreParaColumnFirst = new LayoutParams(pxMoreWandH, pxMoreWandH);
        morePara = new LayoutParams(pxMoreWandH, pxMoreWandH);
        morePara.setMargins(pxImagePadding, 0, 0, 0);

        rowPara = new LayoutParams(match, wrap);
    }

    // 根据imageView的数量初始化不同的View布局,还要为每一个View作点击效果
    private void initView() {
        this.setOrientation(VERTICAL);
        this.removeAllViews();
        if (MAX_WIDTH == 0) {
            //为了触发onMeasure()来测量MultiImageView的最大宽度，MultiImageView的宽设置为match_parent
            addView(new View(getContext()));
            return;
        }

        if (imagesList == null || imagesList.size() == 0) {
            return;
        }

        if (dynamicType == 3) {
            //视频
            addView(createLinear(0, false));
        } else {
            if (imagesList.size() == 1) {
                addView(createLinear(0, false));
            } else {
                int allCount = imagesList.size();
                if (allCount == 4) {
                    MAX_PER_ROW_COUNT = 2;
                } else {
                    MAX_PER_ROW_COUNT = 3;
                }
                int rowCount = allCount / MAX_PER_ROW_COUNT
                        + (allCount % MAX_PER_ROW_COUNT > 0 ? 1 : 0);// 行数
                for (int rowCursor = 0; rowCursor < rowCount; rowCursor++) {
                    LinearLayout rowLayout = new LinearLayout(getContext());
                    rowLayout.setOrientation(LinearLayout.HORIZONTAL);

                    rowLayout.setLayoutParams(rowPara);
                    if (rowCursor != 0) {
                        rowLayout.setPadding(0, pxImagePadding, 0, 0);
                    }

                    int columnCount = allCount % MAX_PER_ROW_COUNT == 0 ? MAX_PER_ROW_COUNT
                            : allCount % MAX_PER_ROW_COUNT;//每行的列数
                    if (rowCursor != rowCount - 1) {
                        columnCount = MAX_PER_ROW_COUNT;
                    }
                    addView(rowLayout);

                    int rowOffset = rowCursor * MAX_PER_ROW_COUNT;// 行偏移
                    for (int columnCursor = 0; columnCursor < columnCount; columnCursor++) {
                        int position = columnCursor + rowOffset;
                        rowLayout.addView(createLinear(position, true));
                    }
                }
            }
        }
    }

    private LinearLayout createLinear(final int position, final boolean isMultiImage) {
        String url_pic = "";
        String url_video = "";
        final SquarePicBean model = imagesList.get(position);
        url_pic = HttpUrlConstant.SERVER_URL + CommonUtils.getRurl(model.getUrl());

        LinearLayout linear = new LinearLayout(getContext());
        linear.setBackgroundResource(R.color.transparent);
        linear.setGravity(Gravity.LEFT);

        ImageView imageView = null;

        if (isMultiImage) {
            imageView = new ColorFilterImageView(getContext());
            imageView.setAdjustViewBounds(true);

            linear.setLayoutParams(position % MAX_PER_ROW_COUNT == 0 ? moreParaColumnFirst : morePara);
            linear.setOrientation(LinearLayout.VERTICAL);
            imageView.setLayoutParams(moreParaColumnFirst);
            imageView.setScaleType(ScaleType.FIT_XY);
            linear.addView(imageView);
        } else {
            if (dynamicType == 3) {
//                linear.setLayoutParams(videoPicPara);
//                linear.setOrientation(LinearLayout.VERTICAL);
//
//                RelativeLayout mRela = (RelativeLayout) LayoutInflater.from(getContext()).inflate(R.layout.layout_video_type, null);
//                mRela.setLayoutParams(videoPicPara);
//                imageView = (ImageView) mRela.findViewById(R.id.id_video_img);
//                linear.addView(mRela);
//                imageView.setMaxHeight(videoMaxWandH * 2 / 3);
            } else {
//                imageView.setMaxHeight(pxOneMaxWandH);
                imageView = new ColorFilterImageView(getContext());
                imageView.setAdjustViewBounds(true);
                linear.setLayoutParams(onePicPara);
                linear.setOrientation(LinearLayout.VERTICAL);

                imageView.setLayoutParams(onePicPara);
                imageView.setScaleType(ScaleType.FIT_CENTER);
                linear.addView(imageView);
            }
        }
//        imageView.setTag(position);
//        imageView.setTag(R.id.aliwx_search_key, position);
        imageView.setId(url_pic.hashCode());
        //图片点击事件
        final String finalUrl_video = url_video;
        imageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mOnItemClickListener != null) {
                    mOnItemClickListener.onItemClick(view, position, dynamicType, finalUrl_video);
                }
            }
        });

        LogUtils.d(url_pic + "[][][[][[]]");
        //图片
        ImageLoader.getInstance().displayImage(url_pic, imageView, ImageUtils.getImageOptions(R.color.pickerview_bg_topbar));
        return linear;
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position, int fileType, String urlVideo);
    }
}